package service

import (
	"hrms-api/model"
	"time"

	"gorm.io/gorm"
)

// AttendanceService 考勤服务
type AttendanceService struct {
	DB *gorm.DB
}

// NewAttendanceService 创建考勤服务
func NewAttendanceService(db *gorm.DB) *AttendanceService {
	return &AttendanceService{DB: db}
}

// CheckIn 员工签到
func (s *AttendanceService) CheckIn(userID uint, date time.Time, location, remark string) (*model.Attendance, error) {
	// 检查用户是否存在
	var user model.User
	if err := s.DB.First(&user, userID).Error; err != nil {
		return nil, err
	}

	// 检查是否已经签到
	var existingAttendance model.Attendance
	result := s.DB.Where("user_id = ? AND date = ?", userID, date.Format("2006-01-02")).First(&existingAttendance)
	if result.Error != gorm.ErrRecordNotFound {
		return nil, result.Error
	}

	// 创建签到记录
	attendance := model.Attendance{
		UserID:   userID,
		Date:     date,
		CheckIn:  time.Now(),
		Status:   1, // 已签到
		Location: location,
		Remark:   remark,
	}

	if err := s.DB.Create(&attendance).Error; err != nil {
		return nil, err
	}

	return &attendance, nil
}

// CheckOut 员工签退
func (s *AttendanceService) CheckOut(userID uint, date time.Time, location, remark string) (*model.Attendance, error) {
	// 获取当天的考勤记录
	var attendance model.Attendance
	result := s.DB.Where("user_id = ? AND date = ?", userID, date.Format("2006-01-02")).First(&attendance)
	if result.Error != nil {
		return nil, result.Error
	}

	// 更新签退信息
	updates := map[string]interface{}{
		"check_out": time.Now(),
		"status":    2, // 已签退
		"location":  location,
		"remark":    remark,
	}

	if err := s.DB.Model(&attendance).Updates(updates).Error; err != nil {
		return nil, err
	}

	return &attendance, nil
}

// ApplyLeave 申请请假
func (s *AttendanceService) ApplyLeave(userID uint, date time.Time, leaveType int, leaveTime float32, remark string) (*model.Attendance, error) {
	// 检查用户是否存在
	var user model.User
	if err := s.DB.First(&user, userID).Error; err != nil {
		return nil, err
	}

	// 创建请假记录
	attendance := model.Attendance{
		UserID:    userID,
		Date:      date,
		Status:    5, // 缺勤（请假）
		LeaveType: leaveType,
		LeaveTime: leaveTime,
		Remark:    remark,
	}

	if err := s.DB.Create(&attendance).Error; err != nil {
		return nil, err
	}

	return &attendance, nil
}

// GetAttendance 获取考勤记录
func (s *AttendanceService) GetAttendance(attendanceID string) (*model.Attendance, error) {
	var attendance model.Attendance
	result := s.DB.Preload("User").First(&attendance, attendanceID)
	if result.Error != nil {
		return nil, result.Error
	}
	return &attendance, nil
}

// ListAttendances 获取考勤记录列表
func (s *AttendanceService) ListAttendances(userID, startDate, endDate string) ([]model.Attendance, error) {
	db := s.DB.Preload("User")

	// 根据用户ID筛选
	if userID != "" {
		db = db.Where("user_id = ?", userID)
	}

	// 根据日期范围筛选
	if startDate != "" {
		db = db.Where("date >= ?", startDate)
	}
	if endDate != "" {
		db = db.Where("date <= ?", endDate)
	}

	var attendances []model.Attendance
	if err := db.Find(&attendances).Error; err != nil {
		return nil, err
	}

	return attendances, nil
}

// GetTodayAttendance 获取今日考勤
func (s *AttendanceService) GetTodayAttendance(userID uint) (*model.Attendance, error) {
	today := time.Now().Format("2006-01-02")

	var attendance model.Attendance
	result := s.DB.Where("user_id = ? AND date = ?", userID, today).First(&attendance)
	if result.Error != nil {
		return nil, result.Error
	}

	return &attendance, nil
}

// GetAttendanceHistory 获取考勤历史
func (s *AttendanceService) GetAttendanceHistory(userID uint, startDate, endDate string) ([]model.Attendance, error) {
	db := s.DB.Where("user_id = ?", userID)

	// 根据日期范围筛选
	if startDate != "" {
		db = db.Where("date >= ?", startDate)
	}
	if endDate != "" {
		db = db.Where("date <= ?", endDate)
	}

	var attendances []model.Attendance
	if err := db.Find(&attendances).Error; err != nil {
		return nil, err
	}

	return attendances, nil
}

// GetAttendanceRecords 获取考勤记录
func (s *AttendanceService) GetAttendanceRecords(userID uint, courseID string) ([]model.Attendance, error) {
	db := s.DB.Where("user_id = ?", userID)

	// 根据课程ID筛选
	if courseID != "" {
		db = db.Where("course_id = ?", courseID)
	}

	var attendances []model.Attendance
	if err := db.Find(&attendances).Error; err != nil {
		return nil, err
	}

	return attendances, nil
}

// GetAttendanceStats 获取考勤统计数据
func (s *AttendanceService) GetAttendanceStats(userID uint, startDate, endDate string) (map[string]int, error) {
	db := s.DB.Model(&model.Attendance{}).Where("user_id = ?", userID)

	// 根据日期范围筛选
	if startDate != "" {
		db = db.Where("date >= ?", startDate)
	}
	if endDate != "" {
		db = db.Where("date <= ?", endDate)
	}

	stats := make(map[string]int)

	// 统计正常考勤
	var normalCount int64
	if err := db.Where("status IN (1, 2)").Count(&normalCount).Error; err != nil {
		return nil, err
	}
	stats["normal"] = int(normalCount)

	// 统计迟到
	var lateCount int64
	if err := db.Where("status = 3").Count(&lateCount).Error; err != nil {
		return nil, err
	}
	stats["late"] = int(lateCount)

	// 统计早退
	var earlyCount int64
	if err := db.Where("status = 4").Count(&earlyCount).Error; err != nil {
		return nil, err
	}
	stats["early"] = int(earlyCount)

	// 统计请假
	var leaveCount int64
	if err := db.Where("status = 5").Count(&leaveCount).Error; err != nil {
		return nil, err
	}
	stats["leave"] = int(leaveCount)

	// 统计缺勤
	var absentCount int64
	if err := db.Where("status = 0").Count(&absentCount).Error; err != nil {
		return nil, err
	}
	stats["absent"] = int(absentCount)

	return stats, nil
}
